{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "dcd22756",
   "metadata": {},
   "source": [
    "iris建模  \n",
    "软件的安装请按视频来进行:  \n",
    "https://www.bilibili.com/video/BV1WoGgeZEmc/?spm_id_from=333.337.search-card.all.click&vd_source=0cbd9d003114983764a9ba3bfd03cf31  \n",
    "VScode + anaconda3环境的配置方法"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ad5cb809",
   "metadata": {},
   "source": [
    "读取文件  \n",
    "数据集文件与代码文件放在同一个目录下"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0bfdc5d3",
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "\n",
    "data = pd.read_csv('Iris.csv')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 70,
   "id": "0e0804e1",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['Iris-setosa' 'Iris-versicolor' 'Iris-virginica']\n"
     ]
    }
   ],
   "source": [
    "data.head(5)\n",
    "print(data['Species'].unique())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 71,
   "id": "5e5550de",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 定义一个方法，将Species转为整数1、2、3\n",
    "def convert(species: str)-> int:\n",
    "    if species == 'Iris-setosa':\n",
    "        return 1\n",
    "    if species == 'Iris-versicolor':\n",
    "        return 2\n",
    "    if species == 'Iris-virginica':\n",
    "        return 3"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "76803884",
   "metadata": {},
   "source": [
    "将属名转换成分类整数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 72,
   "id": "c8ffb746",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 使用列表推导式\n",
    "data['Species'] = [\n",
    "    convert(s) for s in data['Species']\n",
    "]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "76e02cfa",
   "metadata": {},
   "source": [
    "获取建模用的X和Y\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 74,
   "id": "2f4b780c",
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.model_selection import train_test_split\n",
    "\n",
    "x_train, x_test, y_train, y_test = train_test_split(x, y, test_size= 0.25, random_state= 4)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "70593365",
   "metadata": {},
   "source": [
    "开始建模"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 77,
   "id": "3d9a7032",
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.ensemble import RandomForestClassifier\n",
    "\n",
    "rfc = RandomForestClassifier()\n",
    "model = rfc.fit(x_train, y_train)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b328382e",
   "metadata": {},
   "source": [
    "对模型进行评价"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 78,
   "id": "0c8e7efd",
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.metrics import accuracy_score, confusion_matrix, classification_report\n",
    "\n",
    "y_predict = model.predict(x_test)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 80,
   "id": "5e322ca9",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0.9736842105263158\n",
      "[[18  0  0]\n",
      " [ 0  7  1]\n",
      " [ 0  0 12]]\n",
      "              precision    recall  f1-score   support\n",
      "\n",
      "           1       1.00      1.00      1.00        18\n",
      "           2       1.00      0.88      0.93         8\n",
      "           3       0.92      1.00      0.96        12\n",
      "\n",
      "    accuracy                           0.97        38\n",
      "   macro avg       0.97      0.96      0.96        38\n",
      "weighted avg       0.98      0.97      0.97        38\n",
      "\n"
     ]
    }
   ],
   "source": [
    "print(accuracy_score(y_test, y_predict))\n",
    "print(confusion_matrix(y_test, y_predict))\n",
    "print(classification_report(y_test, y_predict))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a80b56e5",
   "metadata": {},
   "source": [
    "预测新的数据的分类情况"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 82,
   "id": "dc013af0",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "c:\\Users\\chang\\anaconda3\\Lib\\site-packages\\sklearn\\utils\\validation.py:2739: UserWarning: X does not have valid feature names, but RandomForestClassifier was fitted with feature names\n",
      "  warnings.warn(\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "array([1])"
      ]
     },
     "execution_count": 82,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "sample = [3.2, 2.6, 0.9, 0.1]\n",
    "import numpy as np\n",
    "np_sample = np.array(sample).reshape(1,4)\n",
    "model.predict(np_sample)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 83,
   "id": "937b8555",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "c:\\Users\\chang\\anaconda3\\Lib\\site-packages\\sklearn\\utils\\validation.py:2739: UserWarning: X does not have valid feature names, but RandomForestClassifier was fitted with feature names\n",
      "  warnings.warn(\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "array([[0.92, 0.08, 0.  ]])"
      ]
     },
     "execution_count": 83,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "model.predict_proba(np_sample)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "953d6724",
   "metadata": {},
   "outputs": [],
   "source": [
    "print(len(data[data['Species']==1]))\n",
    "print(len(data[data['Species']==2]))\n",
    "print(len(data[data['Species']==3]))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 90,
   "id": "9de7024c",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0.32670000000000005\n"
     ]
    }
   ],
   "source": [
    "print(0.33*0.33 + 0.33* 0.33+ 0.33*0.33) # 随机概率"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "87e87689",
   "metadata": {},
   "source": [
    "1、模型如何保存\n",
    "2、如何读取以保存的模型并进行预测"
   ]
  }
 ],
 "metadata": {
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
